package com.example.demo.controller;

import com.example.demo.dto.RegisterRequest;
import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.loginRequest;
import com.example.demo.repository.UserRepository;
import com.example.demo.security.JwtUtils;
import com.example.demo.service.UserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;

    public AuthController(
            AuthenticationManager authenticationManager,
            JwtUtils jwtUtils,
            UserService userService,
            PasswordEncoder passwordEncoder,
            UserRepository userRepository
    ) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.userRepository = userRepository;
    }

    @PostMapping("/register")
    public ApiResponse<String> register(@RequestBody RegisterRequest request) {
        try {
            // 检查用户昵称是否为空
            if (request.name() == null || request.name().isEmpty()) {
                return ApiResponse.error(400, "用户昵称不能为空");
            }

            // 1. 检查用户名是否已存在
            if (userService.existsByUsername(request.username())) {
                return ApiResponse.error(400, "用户名已存在");
            }

            // 检查密码是否为空
            if (request.password() == null || request.password().isEmpty()) {
                return ApiResponse.error(400, "密码不能为空");
            }

            // 2. 创建用户
            userService.createUser(
                    request.name(),
                    request.username(),
                    passwordEncoder.encode(request.password()),
                    "02229d89cc94d086"// 默认普通用户
            );

            return ApiResponse.success("注册成功");
        } catch (Exception e) {
            return ApiResponse.error(500, "注册失败");
        }
    }

    @PostMapping("/login")
    public ApiResponse<List<Map<String, String>>> login(
            @RequestBody loginRequest LoginRequest) {
        try {
            // 1. 认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(LoginRequest.username(), LoginRequest.password())
            );

            if (userService.getStatus(LoginRequest.username()) == 1) {
                return ApiResponse.error(401, "账号已封禁");
            }

            // 2. 生成Token
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String token = jwtUtils.generateToken(userDetails);

            Map<String, String> tokenMap = new LinkedHashMap<>();
            tokenMap.put("id", userService.getID(userDetails.getUsername()));
            tokenMap.put("token", token);
            tokenMap.put("username", userDetails.getUsername());
            String authText = switch(userService.authPress(userDetails.getUsername())) {
                case "e56e1e0d96783898" -> "管理员";
                case "02229d89cc94d086" -> "普通用户";
                default -> "未知角色";
            };
            tokenMap.put("role", authText);
            tokenMap.put("nickname", userService.getName(userDetails.getUsername()));
            tokenMap.put("loginTime", LocalDateTime.now().toString());
            tokenMap.put("status", String.valueOf(userService.getStatus(userDetails.getUsername())));

            List<Map<String, String>> data = Collections.singletonList(tokenMap);

            return ApiResponse.<List<Map<String, String>>>success(200, "登陆成功", data);
        } catch (Exception e) {
            return ApiResponse.<List<Map<String, String>>>error(401, "登录失败");
        }
    }
}